package com.myapp.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DBUtil {
	private static Connection conn = null;
	private static PreparedStatement ps = null;
	private static ResultSet rs = null;

	public static Connection getConn() throws Exception {
		if (conn != null)
			return conn;
		// 连接本地
		String driver = "com.mysql.jdbc.Driver";
		String url = "jdbc:mysql://localhost:3306/myapp?useUnicode=true&amp;characterEncoding=GBK";
		String user = "root";
		String password = "root";

		// 连接百度云
		// String driver = "com.mysql.jdbc.Driver";
		// String url =
		// "jdbc:mysql://sqld.duapp.com:4050/rZBhMRVhjtLjDyIVexlX?useUnicode=true&amp;characterEncoding=GBK";
		// String user = "TWTkGsh3nTkmNrxw9nRCuzgE";
		// String password = "2m6UoghsZxPDAy6im7CQwZpfHC1LyFAc";

		Class.forName(driver);
		conn = DriverManager.getConnection(url, user, password);
		return conn;
	}

	public static int exeUpdate(String sql) throws Exception {
		if (conn == null)
			conn = DBUtil.getConn();
		ps = conn.prepareStatement(sql);
		return ps.executeUpdate();
	}

	public static ResultSet exeQuery(String sql) throws Exception {
		if (conn == null)
			conn = DBUtil.getConn();
		ps = conn.prepareStatement(sql);
		rs = ps.executeQuery();
		return rs;
	}

	public static void closeConn() {
		try {
			if (conn != null) {
				conn.close();
				conn = null;
			}
			if (ps != null) {
				ps.close();
				ps = null;
			}
			if (rs != null) {
				rs.close();
				rs = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
